package com.aloha.springframework.beans.factory.support;

import com.aloha.springframework.beans.BeansException;
import com.aloha.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author DaiZhiHeng
 * @description 使用Java中反射的方法创建对象
 * @date 2023/7/1 21:25
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiate(String beanName, BeanDefinition beanDefinition, Constructor<?> constructor, Object[] args) throws BeansException {
        Class<?> beanClass = beanDefinition.getBeanClass();
        try {
            if (constructor != null) {
                // 构造器不为null，说明使用的是有参的构造函数
                return beanClass.getDeclaredConstructor(constructor.getParameterTypes()).newInstance(args);
            } else {
                // 使用无参的构造函数创建对象
                return beanClass.newInstance();
            }
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new BeansException("在实例化 [" + beanClass.getName() + "] 时出错", e);
        }
    }
}

